<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '',
  },
}
</route>

<template>
  <view class="login-container">
    <view class="flex flex-row justify-center items-center mb-48rpx">
      <wd-img :src="shopLogo" mode="aspectFit" height="150rpx" width="150rpx"></wd-img>
    </view>
    <view class="login-tabs">
      <view :class="['tab', mode === 'login' ? 'active' : '']" @tap="mode = 'login'">账号登录</view>
      <view :class="['tab', mode === 'register' ? 'active' : '']" @tap="mode = 'register'">
        账号注册
      </view>
    </view>
    <view v-if="mode === 'login'">
      <wd-input v-model="loginForm.account" label="账号" placeholder="请输入账号" clearable />
      <wd-input
        v-model="loginForm.password"
        label="密码"
        placeholder="请输入密码"
        clearable
        show-password
      />
      <view class="mt-32rpx">
        <wd-button type="primary" :custom-style="buttonStyle" block @click="handleAccountLogin">
          账号密码登录
        </wd-button>
      </view>

      <view style="margin-top: 24rpx">
        <wd-button
          type="default"
          block
          open-type="getUserInfo"
          @click="handleWxLogin"
          class="wx-login-btn"
        >
          <image src="/static/logo.svg" class="wx-login-icon" mode="aspectFit" />
          <text class="wx-login-text">微信一键登录</text>
        </wd-button>
      </view>
    </view>
    <view v-else>
      <wd-input v-model="registerForm.account" label="账号" placeholder="请输入账号" clearable />
      <wd-input
        v-model="registerForm.password"
        label="密码"
        placeholder="请输入密码"
        show-password
        clearable
      />
      <view class="mt-32rpx">
        <wd-button type="primary" block :custom-style="buttonStyle" @click="handleRegister">
          注册
        </wd-button>
        <view class="switch-tip">
          已有账号？
          <text class="switch-link" @tap="mode = 'login'">去登录</text>
        </view>
      </view>
    </view>
    <MploginPopup
      v-model:show="showLoginPopup"
      :logo="shopLogo"
      title="完善信息"
      @update="handleUpdateUser"
    />
  </view>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { mnpLoginUsingPost } from '@/api/loginController'
import { updateDataUsingPost, centerUsingGet } from '@/api/userController'
import { weixindenglucanshu, xinyonghugengxinxinxicanshu } from '@/api'
import { useUserStore } from '@/store/user'
import MploginPopup from './components/mplogin-popup.vue'

const userStore = useUserStore()
const loginData = ref({})
const showLoginPopup = ref(false)
const shopLogo = ref('/static/car/shop_logo.png')

const mode = ref<'login' | 'register'>('login')
const loginForm = ref({
  account: '',
  password: '',
  scene: 1,
  terminal: 1,
})
const registerForm = ref({
  account: '',
  password: '',
  terminal: 1,
})
const buttonStyle = ref('background-color:#bc5cd7')

function handleAccountLogin() {
  if (!loginForm.value.account || !loginForm.value.password) {
    uni.showToast({ title: '请输入账号和密码', icon: 'none' })
    return
  }
  // TODO: 调用账号密码登录接口
  uni.showToast({ title: '账号密码登录成功（示例）', icon: 'success' })
}

function handleWxLogin() {
  uni.showLoading({
    title: '请稍后...',
  })
  uni.login({
    provider: 'weixin',
    success: async (res) => {
      if (res.code) {
        const { code }: any = await uni.login({
          provider: 'weixin',
        })
        const res = await mnpLoginUsingPost({
          body: {
            code,
          },
        })
        const data = res.data
        loginData.value = data
        if (data.is_new) {
          uni.hideLoading()
          userStore.setTemToken(data.token)
          showLoginPopup.value = true
          return
        }
        loginHandle(data)
        // TODO: 调用微信一键登录接口，参数 { code: res.code, terminal: 1 }
        // uni.showToast({ title: '微信一键登录成功（示例）', icon: 'success' })
      } else {
        uni.showToast({ title: '微信登录失败', icon: 'none' })
      }
    },
    fail: () => {
      uni.showToast({ title: '微信登录失败', icon: 'none' })
    },
  })
}

function handleRegister() {
  if (!registerForm.value.account || !registerForm.value.password) {
    uni.showToast({ title: '请输入账号和密码', icon: 'none' })
    return
  }
  // TODO: 调用注册接口
  uni.showToast({ title: '注册成功（示例）', icon: 'success' })
}

const handleUpdateUser = async (userInfo: xinyonghugengxinxinxicanshu) => {
  const res = await updateDataUsingPost({
    body: { ...userInfo },
    options: {
      url: '/api/user/updateUser', // TODO: Replace with actual URL
      token: userStore.getTemToken(),
    },
  })
  showLoginPopup.value = false
  loginHandle(loginData.value)
}

const loginHandle = async (data: any) => {
  const { token, mobile } = data
  // if (!mobile && isForceBindMobile.value) {
  //   userStore.temToken = token
  //   uni.navigateTo('/pages/bind_mobile/bind_mobile')
  //   uni.hideLoading()
  //   return
  // }
  userStore.setToken(data.token)
  await centerUsingGet({})
  uni.showToast({
    title: '登录成功',
    icon: 'success',
  })
  uni.hideLoading()
  // const pages = getCurrentPages()
  // if (pages.length > 1) {
  //   const prevPage = pages[pages.length - 2]
  //   await uni.navigateBack()
  //   const { onLoad, options } = prevPage
  //   // 刷新上一个页面
  //   onLoad && onLoad(options)
  // } else if (cache.get(BACK_URL)) {
  //   try {
  //     router.switchTab(cache.get(BACK_URL))
  //   } catch (error) {
  //     router.redirectTo(cache.get(BACK_URL))
  //   }
  // } else {
  //   // try {
  //   //     router.reLaunch('/pages/index/index')
  //   // } catch (error) {
  //   uni.switchTab('/pages/index/index')
  //   // }
  // }
  // cache.remove(BACK_URL)
  uni.switchTab({ url: '/pages/index/index' })
}
</script>

<style lang="scss" scoped>
.login-container {
  min-height: 100vh;
  padding: 60rpx 40rpx 0 40rpx;
  background: #f8f8f8;
}
.login-tabs {
  display: flex;
  justify-content: center;
  margin-bottom: 48rpx;
  .tab {
    padding: 0 40rpx 16rpx 40rpx;
    font-size: 32rpx;
    color: #888;
    border-bottom: 4rpx solid transparent;
    &.active {
      font-weight: bold;
      color: #333;
      border-bottom: 4rpx solid #4d80f0;
    }
  }
}
.switch-tip {
  margin-top: 32rpx;
  font-size: 28rpx;
  color: #888;
  text-align: center;
}
.switch-link {
  margin-left: 8rpx;
  color: #4d80f0;
}
.wx-login-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 88rpx;
  padding: 0 24rpx;
  font-size: 32rpx;
  color: #09bb07;
  background: #f6ffed;
  border: 1rpx solid #b7eb8f;
  border-radius: 44rpx;
}
.wx-login-icon {
  width: 40rpx;
  height: 40rpx;
  margin-right: 16rpx;
  vertical-align: middle;
}
.wx-login-text {
  font-size: 32rpx;
  font-weight: bold;
}
</style>
